package com.thb.exception;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.thb.utils.JSONUtil;

public class CommonExceptionHandler implements HandlerExceptionResolver {

	private static final Logger log = LoggerFactory
			.getLogger(CommonExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object object, Exception exception) {
		

			try {
				if (exception instanceof ServiceException) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("code", ((ServiceException) exception).getErrorCode());
					map.put("msg",
							((ServiceException) exception).getErrorName());
					map.put("data", JSONUtil.beanToJson(((ServiceException) exception).getData()));
					response.setCharacterEncoding("UTF-8");
					response.setContentType("application/json;charset=UTF-8");
					PrintWriter writer = response.getWriter();

					String json = JSONUtil.beanToJson(map);
					writer.write(json);
					writer.flush();
					log.info("Exception:************" + json);
					log.info("exception", exception);
					return new ModelAndView();
				}else{
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("code", "5000");
					map.put("msg", "处理数据失败");
					map.put("data", new JSONObject());
					response.setCharacterEncoding("UTF-8");
					response.setContentType("application/json;charset=UTF-8");
					PrintWriter writer = response.getWriter();
					String json = JSONUtil.beanToJson(map);
					writer.write(json);
					writer.flush();
					log.info("Exception:************" + json);
					log.info("exception", exception);
					return new ModelAndView();
				}
			} catch (IOException e) {
				log.info("exception", e);
			}
		
			return new ModelAndView();
	}

}
